package com.joshua.newsdemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.joshua.newsdemo.utils.HtmlService;
import com.joshua.newsdemo.utils.NewsFilter;
import com.joshua.newsdemo.utils.PrintLog;
import com.joshua.newsdemo.utils.StringUtils;
import com.joshua.newsdemo.utils.TLog;

/**
 * @description:
 * @author: JoshuaWong E-mail:joshuawongchn@gmail.com
 * @date: 2017年03月21日 14:49
 * @version: 1.0
 */

public class OWebView extends WebView {
    public OWebView(Context context) {
        super(context);
        init();
    }

    public OWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public OWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public OWebView(Context context, AttributeSet attrs, int defStyleAttr, boolean
            privateBrowsing) {
        super(context, attrs, defStyleAttr, privateBrowsing);
        init();
    }

    @SuppressLint("JavascriptInterface")
    private void init() {
        setClickable(false);
        setFocusable(false);

        setHorizontalScrollBarEnabled(false);
        WebSettings settings = getSettings();
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setDefaultFontSize(14);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);

        Log.w("joshua", "init: ");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            addJavascriptInterface(new OnWebViewImageListener() {
                @Override
                @JavascriptInterface
                public void showImagePreview(String bigImageUrl) {
                    if (bigImageUrl != null && !StringUtils.isEmpty(bigImageUrl)) {
                        //TODO switch to ImageGalleryActivity
                        Log.w("joshua", "showImagePreview: " + bigImageUrl);
                    }
                }
            }, "mWebViewImageListener");
        }
    }

    public void loadDetailDataAsync(final String url) {
        Context context = getContext();
        if (context != null && context instanceof Activity) {
            final Activity activity = (Activity) context;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final NewsBean bean = NewsFilter.filt(HtmlService.getHtml(url));
                        final String body = setupWebContent(bean.getHtml(), true, true,
                                "");
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //loadData(body, "text/html; charset=UTF-8", null);
                                loadDataWithBaseURL("", body, "text/html", "UTF-8", "");
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            TLog.e(OWebView.class.getName(), "loadDetailDataAsync error, the Context " +
                    "isn't ok");
        }
    }

    private static String setupWebContent(String content, boolean isShowHighlight,
                                          boolean isShowImagePreview, String css) {
        if (TextUtils.isEmpty(content) || TextUtils.isEmpty(content.trim()))
            return "";

        content = content.replaceAll("<([u|o])l.*>", "<$1l " +
                "style=\"padding-left:20px\">");

        // 添加点击图片放大支持
//        if (isShowImagePreview) {
//            // TODO 用一个正则就搞定??
//            content = content.replaceAll("<img[^>]+src=\"([^\"\'\\s]+)\"[^>]*>",
//                    "<img src=\"$1\" onClick=\"javascript:mWebViewImageListener" +
//                            ".showImagePreview('$1')\"/>");
//        }
//        } else {
//            // 过滤掉 img标签
//            content = content.replaceAll("<\\s*img\\s+([^>]*)\\s*/>", "");
//        }


        PrintLog.print(content, "output.txt");

        String style = "<style type=\"text/css\">\n" +
                "\tp{\n" +
                "\t\tpadding-left:20px;\n" +
                "\t\tpadding-right:20px;\n" +
                "\t\tborder-color:gray;\n" +
                "\t\tcolor:#212121;\n" +
                "\t}\n" +
                "</style>";

        return String.format(
                "<!DOCTYPE html>"
                        + "<html>"
                        + "<head>"
                        + "%s"
                        + (isShowHighlight ? "<link rel=\"stylesheet\" " +
                        "type=\"text/css\" href=\"file:///android_asset/css/shCore" +
                        ".css\">" : "")
                        + (isShowHighlight ? "<link rel=\"stylesheet\" " +
                        "type=\"text/css\" " +
                        "href=\"file:///android_asset/css/shThemeDefault.css\">" : "")
                        + "<link rel=\"stylesheet\" type=\"text/css\" " +
                        "href=\"file:///android_asset/css/common_detail.css\">"
                        + "%s"
                        + "</head>"
                        + "<body>"
                        + "<div class='body-content'>"
                        + "%s"
                        + "</div>"
                        + (isShowHighlight ? "<script type=\"text/javascript\" " +
                        "src=\"file:///android_asset/shCore.js\"></script>" : "")
                        + (isShowHighlight ? "<script type=\"text/javascript\" " +
                        "src=\"file:///android_asset/brush.js\"></script>" : "")
                        + (isShowHighlight ? "<script " +
                        "type=\"text/javascript\">SyntaxHighlighter.all();</script>" : "")
                        + "</body>"
                        + "</html>"
                , style, (css == null ? "" : css), content);
    }
}

